#!/usr/bin/env python3
import random
import socket
import sys
import time

from scapy.all import IP, TCP, Ether, get_if_hwaddr, get_if_list, sendp

def get_if():
    ifs = get_if_list()
    iface = None
    for i in ifs:
        if "eth0" in i:
            iface = i
            break
    if not iface:
        print("Cannot find eth0 interface")
        exit(1)
    return iface

def main():
    if len(sys.argv) < 4:
        print('pass 3 arguments: <destination> "<message>" <packet_count>')
        exit(1)

    addr = socket.gethostbyname(sys.argv[1])
    message = sys.argv[2]
    packet_count = int(sys.argv[3])
    iface = get_if()

    print(f"Sending {packet_count} packets on interface {iface} to {addr}")

    for i in range(packet_count):
        # Use random source port for better hash distribution
        sport = random.randint(49152, 65535)
        pkt = Ether(src=get_if_hwaddr(iface), dst='ff:ff:ff:ff:ff:ff')
        pkt = pkt / IP(dst=addr) / TCP(dport=1234, sport=sport) / f"{message}-{i+1}"

        if i < 3:  # Only show first 3 packets
            print(f"Packet {i+1}:")
            pkt.show2()

        sendp(pkt, iface=iface, verbose=False)

        if packet_count > 10 and (i+1) % 10 == 0:
            print(f"Sent {i+1} packets...")

        time.sleep(0.01)  # Small delay between packets

    print(f"Completed sending {packet_count} packets")

if __name__ == '__main__':
    main()
